const {
  registerUser,
  findUser,
  updateUserInfo
} = require("../model/usersModel");
const { sendEmail } = require("../utils/sendEmail");
const cookieParser = require('cookie-parser')
//引入加密模块
const bcrypt = require("bcrypt");
//注册
const register = async (req, res) => {
  let { username, password, code, email } = req.body;
  let randomCode = "";
  //code为0表示获取验证码
  if (code === "0") {
    //随机生成6位验证码
    let str = "0123456789";
    let arr = [];
    for (let i = 0; i < 6; i++) {
      let num = Math.ceil(Math.random() * 9);
      arr.push(str[num]);
    }
    randomCode = arr.join("");
    let result = await sendEmail(email, randomCode);
    if (result) {
      //此处的判断不一定正确

      //存cookie
      res.cookie(email,randomCode,{signed:true,maxAge:1000*60*5})//5分钟后失效

      res.send({ httpStatus: 200, msg: "邮件发送成功" });
    } else {
      res.send({ httpStatus: 400, msg: "邮件发送出错" });
    }
  } else {
    let isUnique = await findUser({ username });
    if (isUnique.length) {
      //表示已存在该用户
      res.send({ httpStatus:400, msg: "用户名已存在" });
    } else {
        //获取cookie并与传来的code对比
        const signedCode=req.signedCookies[email];
      if (code === signedCode) {
          
        //生成随机id 使用13位时间戳加7个随机数的方式
        let id = "";
        let str = "0123456789";
        let arr = [];
        for (let i = 0; i < 7; i++) {
          let num = Math.ceil(Math.random() * 9);
          arr.push(str[num]);
        }
        id = new Date().getTime() + arr.join("");

        //对密码进行加密
        let salt = 10;
        let hashPassword = await bcrypt.hash(password, salt);
        req.body.password = hashPassword;
        req.body.id = id;
        let result = await registerUser(req.body);
        if (result) {
          res.send({ httpStatus: 200, msg: "注册成功" });
        } else {
          res.send({ httpStatus: 400, msg: "注册失败" });
        }
      }else{
        res.send({ httpStatus: 400, msg: "验证码有误" });
      }
    }
  }
};
//登入
const login = async (req, res) => {
  let { username, password } = req.body;
  let query = { username };
  const result = await findUser(query);
  if (result.length) {
    //用户存在时校验密码
    let hashPassword = result[0].password;
    let id = result[0]["id"];
    let verify = await bcrypt.compare(password, hashPassword);
    if (verify) {
      let userInfo = {
        username: result[0]["username"],
        nickname: result[0]["nickname"]
      };
      //将用户信息挂载到当前请求的session上面
      // req.session.userInfo = userInfo;
      res.send({ httpStatus: 200, msg: '登入成功',id,username })
      // res.send({ httpStatus: 200, msg: "登入成功", id: "1", username });
    } else {
      res.send({ httpStatus: 400, msg: "密码错误" });
    }
  } else {
    res.send({ httpStatus: 400, msg: "用户不存在" });
  }
};
//获取所有用户
const getUsers = async (req, res) => {
  //分页
  // let { page, count, username } = req.query;
  // let limit = count ? count - 0 : 10; //转成number类型
  // let skip = page ? (page - 1) * limit : 0;
  // let pagination = {
  //   skip,
  //   limit
  // };
  // //查询指定用户
  // let query = username ? { username } : null;
  // let result = await findUser(query, pagination);
  // res.send({ result });
  let result =await findUser(req.query)
  if(result.length){
    res.send({httpStatus:200,data:result})
  }else{
    res.send({httpStatus:400,data:[]})
  }
};
//修改用户密码
const updatePassword = async (req, res) => {
  //用旧密码更新新密码
  let { username, oldPassword, newPassword } = req.body;
  let isUnique = await findUser({ username });
  if (isUnique.length) {
    //表存在该用户
    let hashPassword = isUnique[0].password;
    let verify = await bcrypt.compare(oldPassword, hashPassword);
    if (verify) {
      //密码比对成功
      let salt = 10;
      let newHashPassword = await bcrypt.hash(newPassword, salt);

      //声明更新条件
      let query = { username };
      let updated = { $set: { password: newHashPassword } };
      let updateResult = await updateUserInfo(query, updated);
      if (updateResult.n) {
        res.send({ httpStatus: 200, msg: "密码修改成功" });
      } else {
        res.send({ httpStatus: 400, msg: "密码修改出错" });
      }
    } else {
      res.send({ httpStatus: 400, msg: "旧密码有误" });
    }
  } else {
    res.send({ httpStatus: 400, msg: "该用户不存在" });
  }
};

const uploadAvatar=async (req,res,next)=>{
  const {id}=req.body;
  let updated={$set:{avatar:req.body.avatarUrl}}
  let result =await updateUserInfo({id},updated);
  if(result.n){
      res.send({httpStatus:200,msg:'图片上传成功'})
      next()
  }else{
      res.send({httpStatus:400,msg:'图片上传失败'})
      // next();
  }
  next()
}
//退出
const quit = (req, res) => {
  req.session.destroy();
  res.send({ httpStatus: 200, msg: "退出登入" });
};
module.exports = {
  register,
  login,
  getUsers,
  uploadAvatar,
  updatePassword,
  quit
};
